package service

import (
	"crypto/tls"
	"fmt"
	"strconv"
	"strings"

	gomail "gopkg.in/mail.v2"

	"net/smtp"

	"github.com/gin-gonic/gin"
	"github.com/jordan-wright/email"

	"tool/global"
)

type Email struct {
	ServiceBase
	Smtp     string
	Port     string
	Authcode string
	From     string
}

func (s Email) Index(c *gin.Context) {
	s.Show("mail", nil, c)
}

// 发送邮件
func (s Email) MailSend(c *gin.Context) {

	addressee := c.DefaultPostForm("addressee", "")
	theme := c.DefaultPostForm("theme", "")
	content := c.DefaultPostForm("content", "")

	if addressee == "" {
		fmt.Println("收件人 为空")
	}
	if theme == "" {
		fmt.Println("主题 为空")
	}
	if content == "" {
		fmt.Println("内容 为空")
	}
	addrs := strings.Split(addressee, ",")

	if len(addrs) > 1 {
		//群发
		s.groupSend(addrs, theme, content)
	} else {
		s.send(addressee, theme, content)
	}
}

// 发送多发(单发接收者为1)
func (s Email) groupSend(to []string, title string, content string) (string, error) {

	e := email.NewEmail()
	e.To = to
	e.From = global.Conf["mailFrom"]
	e.Subject = title
	e.HTML = []byte(content)

	auth := smtp.PlainAuth("", global.Conf["mailFrom"], global.Conf["mailAuthcode"], global.Conf["mailSmtp"])
	var err error
	err = e.SendWithTLS(global.Conf["mailSmtp"]+":"+global.Conf["mailPort"], auth, &tls.Config{ServerName: global.Conf["mailSmtp"]})
	if err != nil {
		return "", err
	}
	return "success", nil
}

// 邮件单位
func (s Email) send(to string, title string, content string) (string, error) {
	port, _ := strconv.Atoi(global.Conf["mailPort"])
	m := gomail.NewMessage()
	m.SetHeader("From", global.Conf["mailFrom"])
	m.SetHeader("To", to)
	m.SetHeader("Subject", title)
	m.SetBody("text/plain", content)
	d := gomail.NewDialer(global.Conf["mailSmtp"], port, global.Conf["mailFrom"], global.Conf["mailAuthcode"])
	d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
	if err := d.DialAndSend(m); err != nil {
		return "", err
	}
	return "success2", nil
}
